package id.co.shuba.spamobile.activities;

import java.io.File;
import java.util.Date;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.CustomSessionApplication;
import id.co.shuba.spamobile.LogoutReceiver;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.Sessions;
import id.co.shuba.spamobile.R.layout;
import id.co.shuba.spamobile.R.menu;
import id.co.shuba.spamobile.data.DatabaseHandler;
import id.co.shuba.spamobile.task.SaveXMLTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;

public class SpadaSyncActivity extends Activity {
	private LogoutReceiver logoutReceiver;

	private void setUpLogoutReceiver() {
		IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction("id.co.shuba.spamobile.ACTION_LOGOUT");
	    logoutReceiver = new LogoutReceiver(this);
	    registerReceiver(logoutReceiver, intentFilter);
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spada_sync);
        unregisterReceiver(logoutReceiver);
        
        save();
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_spada_sync, menu);
        return true;
    }      

    @Override
	public void onUserInteraction() {		
		super.onUserInteraction();
		((CustomSessionApplication) getApplication()).touch();
		if (App.DEBUG) {			
			Log.d("User Interaction", "User interaction to "+this.toString());			
		}
	}
    
    private void save() {
		DatabaseHandler db = new DatabaseHandler(this);		
		ProgressDialog dialog = new ProgressDialog(this);
		dialog.setMessage("Exporting...");
		
		SaveXMLTask task = new SaveXMLTask(db, dialog, Sessions.getUser(this));
		
		File sdPat = Environment.getExternalStorageDirectory();
		File spamobilePath = new File(sdPat, "spamobile");
						
		if (!spamobilePath.exists())
			spamobilePath.mkdirs();
		
		File file = new File(spamobilePath, "temp.pkg");		
		if (file.exists())
			spamobilePath.delete();
		
		task.execute(file.getPath());		
		
		db.close();
	}
}
